package com.ruoyi.common.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.security.SecureRandom;

/**
 * 密码加密工具类
 * 使用AES加密算法对密码进行加密和解密
 * 
 * @author ruoyi
 * @date 2025-08-18
 */
@Component
public class PasswordEncryptionUtils {
    
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    
    @Value("${password.encryption.key:}")
    private String encryptionKey;
    
    /**
     * 生成随机AES密钥（Base64编码）
     * @return Base64编码的密钥字符串
     */
    public static String generateKey() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
            keyGenerator.init(256, new SecureRandom());
            SecretKey secretKey = keyGenerator.generateKey();
            return Base64.getEncoder().encodeToString(secretKey.getEncoded());
        } catch (Exception e) {
            throw new RuntimeException("生成加密密钥失败", e);
        }
    }
    
    /**
     * 加密密码
     * @param password 原始密码
     * @return 加密后的密码（Base64编码）
     */
    public String encrypt(String password) {
        if (password == null || password.isEmpty()) {
            return password;
        }
        
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(
                Base64.getDecoder().decode(encryptionKey), ALGORITHM);
            
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            
            byte[] encryptedBytes = cipher.doFinal(password.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException("密码加密失败", e);
        }
    }
    
    /**
     * 解密密码
     * @param encryptedPassword 加密后的密码（Base64编码）
     * @return 原始密码
     */
    public String decrypt(String encryptedPassword) {
        if (encryptedPassword == null || encryptedPassword.isEmpty()) {
            return encryptedPassword;
        }
        
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(
                Base64.getDecoder().decode(encryptionKey), ALGORITHM);
            
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            
            byte[] decryptedBytes = cipher.doFinal(
                Base64.getDecoder().decode(encryptedPassword));
            return new String(decryptedBytes, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("密码解密失败", e);
        }
    }
    
    /**
     * 静态方法：使用指定密钥加密密码
     * @param password 原始密码
     * @param key Base64编码的密钥
     * @return 加密后的密码（Base64编码）
     */
    public static String encryptWithKey(String password, String key) {
        if (password == null || password.isEmpty()) {
            return password;
        }
        
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(
                Base64.getDecoder().decode(key), ALGORITHM);
            
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            
            byte[] encryptedBytes = cipher.doFinal(password.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException("密码加密失败", e);
        }
    }
    
    /**
     * 静态方法：使用指定密钥解密密码
     * @param encryptedPassword 加密后的密码（Base64编码）
     * @param key Base64编码的密钥
     * @return 原始密码
     */
    public static String decryptWithKey(String encryptedPassword, String key) {
        if (encryptedPassword == null || encryptedPassword.isEmpty()) {
            return encryptedPassword;
        }
        
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(
                Base64.getDecoder().decode(key), ALGORITHM);
            
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            
            byte[] decryptedBytes = cipher.doFinal(
                Base64.getDecoder().decode(encryptedPassword));
            return new String(decryptedBytes, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("密码解密失败", e);
        }
    }
}